package cn.FagDegrn.chatbot.api.domain.ai.service;

import cn.FagDegrn.chatbot.api.domain.ai.IOpenAI;
import cn.FagDegrn.chatbot.api.domain.ai.model.aggregates.AIAnswer;
import cn.FagDegrn.chatbot.api.domain.ai.model.vo.Choices;
import cn.FagDegrn.chatbot.api.domain.zsxq.service.ZsxqApi;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class OpenAI implements IOpenAI {
    @Value("${chatai-api.ApiKey}")
    private String ApiKey;

    private Logger logger= LoggerFactory.getLogger(ZsxqApi.class);
    @Override
    public String doChatGPT(String question) throws IOException {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost post = new HttpPost("https://open.bigmodel.cn/api/paas/v4/chat/completions");

        post.addHeader("Content-Type","application/json");
        post.addHeader("Authorization"," Bearer "+ApiKey);

        String paramJson="{\n" +
                "    \"model\": \"glm-4\",\n" +
                "    \"messages\": [\n" +
                "        {\n" +
                "            \"role\": \"user\",\n" +
                "            \"content\": \""+question+"\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        StringEntity stringEntity = new StringEntity(paramJson, ContentType.create("text/json","UTF-8"));
        post.setEntity(stringEntity);

        CloseableHttpResponse response = httpClient.execute(post);
        if(response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
            String jsonStr = EntityUtils.toString(response.getEntity());
            AIAnswer aiAnswer = JSON.parseObject(jsonStr, AIAnswer.class);

            List<Choices> choices = aiAnswer.getChoices();

            StringBuilder stringBuilder = new StringBuilder();

            for (Choices choice : choices) {
                String content = choice.getMessage().getContent();
                stringBuilder.append(content);
            }

            /*StringBuilder answers = new StringBuilder();
            List<Choices> choices = aiAnswer.getChoices();
            for (Choices choice : choices) {
                System.out.println(choice);
                answers.append(choice);
            }*/


            logger.info("ai响应结果为"+jsonStr);
            logger.info("answers:"+stringBuilder);


            return stringBuilder.toString();

        }else{
           throw new RuntimeException("openAi interface err:"+response.getStatusLine().getStatusCode());
        }

    }
}
